package cn.iocoder.yudao.module.system.controller.admin.gugu;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.system.controller.admin.gugu.gugu.*;
import cn.iocoder.yudao.module.system.service.gugu.CollegeEnrollmentPlanService;
import cn.iocoder.yudao.module.system.util.gugu.GuGuDataUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.util.*;

/**
 * 历年高校招生计划查询 Controller
 */
@Tag(name = "管理后台 - 历年高校招生计划查询")
@RestController
@RequestMapping("/system/college-enrollment-plan")
@Validated
public class CollegeEnrollmentPlanController {

    @Resource
    private CollegeEnrollmentPlanService collegeEnrollmentPlanService;

    @GetMapping("/query")
    @Operation(summary = "查询历年高校招生计划数据")
    @PermitAll
    public CommonResult<CollegeEnrollmentPlanQueryRespVO> queryCollegeEnrollmentPlan(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "页码") @RequestParam(value = "pageIndex") @Min(value = 1, message = "页码不能小于1") Integer pageIndex,
            @Parameter(description = "每页数据量，取值范围在 10 ~ 100 之间（含）") @RequestParam(value = "pageSize") @Min(value = 10, message = "每页数据量不能小于10") @Max(value = 100, message = "每页数据量不能大于100") Integer pageSize,
            @Parameter(description = "查询的高校专业名称，支持模糊查询") @RequestParam(value = "collegeMajorName", required = false) String collegeMajorName,
            @Parameter(description = "查询的招生年份，如 2020、2021、2022、2023、2024。参数默认值为 0：即获取所有年份的招生计划数据") @RequestParam(value = "year", required = false, defaultValue = "0") Integer year,
            @Parameter(description = "查询的高校名称，支持模糊查询") @RequestParam(value = "schoolName", required = false) String schoolName,
            @Parameter(description = "查询的招生省份") @RequestParam(value = "provinceName", required = false) String provinceName,
            @Parameter(description = "查询的专业大类") @RequestParam(value = "classOne", required = false) String classOne,
            @Parameter(description = "查询的专业小类") @RequestParam(value = "classTwo", required = false) String classTwo,
            @Parameter(description = "录取批次参数") @RequestParam(value = "batchName", required = false) String batchName,
            @Parameter(description = "文理综合类别") @RequestParam(value = "type", required = false) String type,
            @Parameter(description = "咕咕数据平台高校唯一 ID") @RequestParam(value = "schoolUuid", required = false) String schoolUuid,
            @Parameter(description = "专业组") @RequestParam(value = "specialGroup", required = false) String specialGroup,
            @Parameter(description = "专业代码") @RequestParam(value = "specialCode", required = false) String specialCode,
            @Parameter(description = "专业组名称") @RequestParam(value = "specialGroupName", required = false) String specialGroupName) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        // 构建请求参数
        CollegeEnrollmentPlanQueryReqVO reqVO = new CollegeEnrollmentPlanQueryReqVO();
        reqVO.setPageIndex(pageIndex);
        reqVO.setPageSize(pageSize);
        reqVO.setCollegeMajorName(collegeMajorName);
        reqVO.setYear(year);
        reqVO.setSchoolName(schoolName);
        reqVO.setProvinceName(provinceName);
        reqVO.setClassOne(classOne);
        reqVO.setClassTwo(classTwo);
        reqVO.setBatchName(batchName);
        reqVO.setType(type);
        reqVO.setSchoolUuid(schoolUuid);
        reqVO.setSpecialGroup(specialGroup);
        reqVO.setSpecialCode(specialCode);
        reqVO.setSpecialGroupName(specialGroupName);

        try {
            // 使用缓存服务获取招生计划信息
            Map<String, Object> result = collegeEnrollmentPlanService.getCollegeEnrollmentPlanInfo(reqVO);

            if (Boolean.TRUE.equals(result.get("success"))) {
                // 构建响应对象
                CollegeEnrollmentPlanQueryRespVO respVO = new CollegeEnrollmentPlanQueryRespVO();
                respVO.setEnrollmentPlanList((List<CollegeEnrollmentPlanInfo>) result.get("enrollmentPlanList"));
                respVO.setTotalCount((Integer) result.get("totalCount"));
                respVO.setPageIndex((Integer) result.get("pageIndex"));
                respVO.setPageSize((Integer) result.get("pageSize"));
                respVO.setTotalPages((Integer) result.get("totalPages"));

                return CommonResult.success(respVO);
            } else {
                return CommonResult.error(500, (String) result.get("message"));
            }
        } catch (Exception e) {
            return CommonResult.error(500, "查询历年高校招生计划数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/validate-key")
    @Operation(summary = "验证历年高校招生计划API Key")
    @PermitAll
    public CommonResult<Boolean> validateApiKey(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey) {

        boolean isValid = GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey);
        return CommonResult.success(isValid);
    }

    @GetMapping("/batch-names")
    @Operation(summary = "获取录取批次枚举值")
    @PermitAll
    public CommonResult<String[]> getBatchNames() {
        String[] batchNames = {
            "专科批", "专科批A段", "专科批F段", "专科提前批", "专科提前批A段", "专科提前批B段", "专科提前批E段",
            "体育类本科批", "体育类第一段", "国家专项计划", "国家专项计划本科批", "地方专项计划本科批",
            "平行录取一段", "提前一批本科", "提前二批本科", "提前批", "提前批第一批本科", "提前批第二批专科",
            "提前批第二批本科", "普通类一段", "普通类二段", "普通类平行录取", "普通类平行录取段", "普通类提前批",
            "本科A段", "本科一批", "本科一批A1段", "本科一批A段", "本科一批B段", "本科一批I段", "本科一批T段",
            "本科一批U段", "本科一段", "本科三批", "本科三批A段", "本科二批", "本科二批A段", "本科二批B段",
            "本科二批C段", "本科二批K段", "本科二批及预科", "本科二段", "本科免费定向批", "本科批", "本科批A段",
            "本科批B段", "本科批C段", "本科提前一批", "本科提前二批", "本科提前批", "本科提前批A段", "本科提前批B段",
            "本科提前批C段", "本科第一批", "本科第一批提前批", "本科第二批", "本科第二批提前批", "本科综合评价批",
            "特殊类型招生批", "艺术本科A段", "艺术本科二批", "艺术本科批A段", "艺术本科批B段", "艺术本科批C段",
            "艺术本科提前批B段", "艺术类本科A段", "艺术类本科批", "艺术类第一批A段", "艺术类第二批", "零志愿批次",
            "零批次", "高校专项计划本科批", "高职（专科）批R段"
        };
        return CommonResult.success(batchNames);
    }

    @GetMapping("/types")
    @Operation(summary = "获取文理综合类别枚举值")
    @PermitAll
    public CommonResult<String[]> getTypes() {
        String[] types = {
            "理科", "文科", "综合", "艺术类", "体育类", "体育理", "蒙授理科", "艺术文", "体育文", "汉授美术",
            "蒙授文科", "学考文", "学考理", "艺术理", "汉授音乐", "汉授体育", "其他艺术", "汉授编导", "蒙授音乐",
            "蒙授体育", "蒙授美术", "旅游类", "计算机类", "3+证书", "蒙授其他艺术", "农学类", "财会类", "牧医类",
            "蒙牧医类", "美工设计类", "汽驾类", "幼师类", "建筑类", "烹饪类"
        };
        return CommonResult.success(types);
    }

    @PostMapping("/batch-import")
    @Operation(summary = "批量导入历年高校招生计划数据")
    @PermitAll
    public CommonResult<Map<String, Object>> batchImportEnrollmentPlanData(
            @Parameter(description = "APPKEY") @RequestParam(value = "appkey",required = false,defaultValue = "8N9BFH4DPAXWL4JJB5WAJYBJ3QCL77FM") String appkey,
            @Parameter(description = "年份列表，如2025,2024,2023,2022") @RequestParam(value = "years", required = false, defaultValue = "2025,2024,2023,2022") String years,
            @Parameter(description = "是否使用多线程") @RequestParam(value = "useMultiThread", required = false, defaultValue = "true") Boolean useMultiThread) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            // 解析年份列表
            List<Integer> yearList = Arrays.stream(years.split(","))
                    .map(String::trim)
                    .map(Integer::parseInt)
                    .collect(java.util.stream.Collectors.toList());

            // 执行批量导入
            Map<String, Object> result = collegeEnrollmentPlanService.batchImportEnrollmentPlanData(yearList, useMultiThread);

            if (Boolean.TRUE.equals(result.get("success"))) {
                return CommonResult.success(result);
            } else {
                return CommonResult.error(500, (String) result.get("message"));
            }
        } catch (Exception e) {
            return CommonResult.error(500, "批量导入历年高校招生计划数据失败: " + e.getMessage());
        }
    }

    @PostMapping("/import-by-province")
    @Operation(summary = "按省份导入指定年份的招生计划数据")
    @PermitAll
    public CommonResult<Integer> importEnrollmentPlanDataByProvince(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "省份名称", required = true) @RequestParam(value = "provinceName") String provinceName,
            @Parameter(description = "年份", required = true) @RequestParam(value = "year") Integer year) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            int importedCount = collegeEnrollmentPlanService.importEnrollmentPlanDataByProvince(provinceName, year);
            return CommonResult.success(importedCount);
        } catch (Exception e) {
            return CommonResult.error(500, "导入招生计划数据失败: " + e.getMessage());
        }
    }

    @GetMapping("/import-progress")
    @Operation(summary = "获取导入进度统计")
    @PermitAll
    public CommonResult<Map<String, Object>> getImportProgress(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            Map<String, Object> progress = collegeEnrollmentPlanService.getImportProgress();

            if (Boolean.TRUE.equals(progress.get("success"))) {
                return CommonResult.success(progress);
            } else {
                return CommonResult.error(500, (String) progress.get("message"));
            }
        } catch (Exception e) {
            return CommonResult.error(500, "获取导入进度统计失败: " + e.getMessage());
        }
    }

    @GetMapping("/query-from-database")
    @Operation(summary = "从数据库查询招生计划数据")
    @PermitAll
    public CommonResult<List<Object>> queryFromDatabase(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "学校名称") @RequestParam(value = "schoolName", required = false) String schoolName,
            @Parameter(description = "专业名称") @RequestParam(value = "majorName", required = false) String majorName,
            @Parameter(description = "省份名称") @RequestParam(value = "provinceName", required = false) String provinceName,
            @Parameter(description = "年份") @RequestParam(value = "year", required = false) Integer year) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            List<cn.iocoder.yudao.module.system.dal.dataobject.collegeenrollmentplan.CollegeEnrollmentPlanDO> planList =
                collegeEnrollmentPlanService.getEnrollmentPlanFromDatabase(schoolName, majorName, provinceName, year);

            // 转换为通用对象返回
            List<Object> result = new java.util.ArrayList<>(planList);
            return CommonResult.success(result);
        } catch (Exception e) {
            return CommonResult.error(500, "查询招生计划数据失败: " + e.getMessage());
        }
    }

    @PostMapping("/test-single-province")
    @Operation(summary = "测试单个省份数据导入")
    @PermitAll
    public CommonResult<Map<String, Object>> testSingleProvinceImport(
            @Parameter(description = "APPKEY", required = true) @RequestParam(value = "appkey") String appkey,
            @Parameter(description = "省份名称", required = false) String provinceName,
            @Parameter(description = "年份", required = false) Integer year) {

        // 验证appkey是否有效
        if (!GuGuDataUtils.validateCollegeEnrollmentPlanApiKey(appkey)) {
            return CommonResult.error(403, "无效的APPKEY");
        }

        try {
            long startTime = System.currentTimeMillis();
            int importedCount = collegeEnrollmentPlanService.importEnrollmentPlanDataByProvince(provinceName, year);
            long endTime = System.currentTimeMillis();

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("provinceName", provinceName);
            result.put("year", year);
            result.put("importedCount", importedCount);
            result.put("duration", endTime - startTime);
            result.put("message", String.format("成功导入%s省%d年的%d条招生计划数据，耗时%d毫秒",
                    provinceName, year, importedCount, endTime - startTime));

            return CommonResult.success(result);
        } catch (Exception e) {
            return CommonResult.error(500, "测试导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/group-query")
    @Operation(summary = "分组查询招生计划数据")
    @PermitAll
    public CommonResult<CollegeEnrollmentPlanGroupRespVO> groupQueryEnrollmentPlan(
            @Parameter(description = "页码") @RequestParam(value = "pageNo") @Min(value = 1, message = "页码不能小于1") Integer pageNo,
            @Parameter(description = "每页数据量，取值范围在 10 ~ 100 之间（含）") @RequestParam(value = "pageSize") @Min(value = 10, message = "每页数据量不能小于10") @Max(value = 100, message = "每页数据量不能大于100") Integer pageSize,
            @Parameter(description = "分组类型：school-按学校分组，major-按专业分组", required = true) @RequestParam(value = "groupType") String groupType,
            @Parameter(description = "查询的高校专业名称，支持模糊查询") @RequestParam(value = "collegeMajorName", required = false) String collegeMajorName,
            @Parameter(description = "查询的高校名称，支持模糊查询") @RequestParam(value = "schoolName", required = false) String schoolName,
            @Parameter(description = "查询的招生省份") @RequestParam(value = "provinceName", required = false) String provinceName,
            @Parameter(description = "查询的专业大类") @RequestParam(value = "classOne", required = false) String classOne,
            @Parameter(description = "查询的专业小类") @RequestParam(value = "classTwo", required = false) String classTwo,
            @Parameter(description = "录取批次参数") @RequestParam(value = "batchName", required = false) String batchName,
            @Parameter(description = "文理综合类别") @RequestParam(value = "type", required = false) String type,
            @Parameter(description = "咕咕数据平台高校唯一 ID") @RequestParam(value = "schoolUuid", required = false) String schoolUuid,
            @Parameter(description = "查询的招生年份，如 2020、2021、2022、2023、2024。参数默认值为 0：即获取所有年份的招生计划数据") @RequestParam(value = "year", required = false, defaultValue = "0") Integer year) {

        // 验证分组类型
        if (!"school".equals(groupType) && !"major".equals(groupType)) {
            return CommonResult.error(400, "分组类型只能是 school 或 major");
        }

        // 构建请求参数
        CollegeEnrollmentPlanGroupQueryReqVO reqVO = new CollegeEnrollmentPlanGroupQueryReqVO();
        reqVO.setPageNo(pageNo);
        reqVO.setPageSize(pageSize);
        reqVO.setGroupType(groupType);
        reqVO.setCollegeMajorName(collegeMajorName);
        reqVO.setSchoolName(schoolName);
        reqVO.setProvinceName(provinceName);
        reqVO.setClassOne(classOne);
        reqVO.setClassTwo(classTwo);
        reqVO.setBatchName(batchName);
        reqVO.setType(type);
        reqVO.setSchoolUuid(schoolUuid);
        reqVO.setYear(year);

        try {
            CollegeEnrollmentPlanGroupRespVO respVO = collegeEnrollmentPlanService.getEnrollmentPlanGroupData(reqVO);
            return CommonResult.success(respVO);
        } catch (Exception e) {
            return CommonResult.error(500, "分组查询招生计划数据失败: " + e.getMessage());
        }
    }

}
